package com.ctcemti.mdm.common.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * Copyright © 2018 YouoTech Of China,All Right Reserved.
 *
 * @PackageName: com.youotech.olm.util
 * @ProjectName: youotech_olm
 * @Description:
 * @version: v1.0.0
 * @author: LiNan Email:linan@youotech.com
 * @date: 2018-08-09 14:40
 * <p>
 * Modification History:
 * Date         Author          Version            Description
 * ---------------------------------------------------------*
 * 2018/8/9     linan           v1.0.0               修改原因
 */
@Slf4j
public class DownloadUtils {

//    private static final String DOWNLOAD_FILE_ENCODING = "UTF-8";

    private static final String DOWNLOAD_FILE_ENCODING = "ISO8859-1";

    /**
     * 下载文件工具类
     * @param response
     * @param path     文件服务器绝对地址
     * @param fileName 下载时的文件名
     */
    public static void downloadFile(HttpServletResponse response, String path, String fileName) {
        try (ServletOutputStream outputStream = response.getOutputStream();
             InputStream inputStream = new FileInputStream(path)) {
            if (!StringUtils.hasText(fileName)) {
                File file = new File(path);
                if (!file.exists()) {
                    log.error("文件不存在！");
                    return;
                }
                fileName = file.getName();
            }
            response = setDownloadResponse(response, fileName);
            byte[] b = new byte[64];
            int length;
            while ((length = inputStream.read(b)) > 0) {
                outputStream.write(b, 0, length);
            }
            outputStream.flush();
            outputStream.close();
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static HttpServletResponse setDownloadResponse(HttpServletResponse response, String fileName) {
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/octet-stream;charset=utf-8");
        try {
            response.setHeader("Content-Disposition", "attachment;filename="
                    + new String(fileName.getBytes(), DOWNLOAD_FILE_ENCODING));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return response;
    }

}
